const Router = require('koa-router')
const { Readable } = require('stream')

const log4 = require('../../utils/log4')()

let router = new Router({
	prefix: '/v1/index'
})

// 写入数据
const send = (stream, event, data) => {
	return stream.push(`event:${event}\ndata: ${JSON.stringify(data)}\n\n`)
}

router.all('/es', async (ctx) => {
	// 创建流
	const reader = new Readable()
	reader._read = function (data) {
		console.log('>')
	}

	ctx.set({
		'Content-Type': 'text/event-stream',
		'Cache-Control': 'no-cache',
		Connection: 'keep-alive'
	})

	send(reader, 'test', { data: 111 })

	ctx.body = reader
	let count = 1
	// 模拟消息发送
	const timer = setInterval(() => {
		send(reader, 'test', { data: 111, count: count++ })
	}, 3000)

	// 处理连接断开
	ctx.req.on('close', () => {
		console.log('close')
		clearInterval(timer)
		reader.destroy()
	})
})
module.exports = router
